import React, { ReactNode, useEffect, useState } from 'react'
import { FormModal } from '@/app/component/form-modal';
import '@/app/component/form.css'
import classNames from 'classnames';
import { ChevronDown, X } from 'lucide-react';
import { MySelect, SelectOption } from '@/app/component/my-select';
import { findIndex } from 'lodash';
import MyInput from '../my-input';

interface MyRangerProps {
  value?: (number | undefined)[]
  onChange?: (value: (number | undefined)[]) => void
  placeholder?: string // 占位符
  className?: string // 自定义类名
  prefix?: ReactNode // 前缀
  suffix?: ReactNode // 后缀
  disabled?: boolean // 禁用
  options: SelectOption<number>[] // 选项
  name?: string // 组件名
}

const MyRanger = <T, IsNumber extends boolean = false>({
  value,
  onChange,
  placeholder,
  className,
  prefix,
  suffix,
  disabled, 
  options,
  name = ''
}: MyRangerProps) => {
  const [open, setOpen] = useState(false)
  // 临时存储的value
  const [tempValue1, setTempValue1] = useState<number | undefined>(value?.[0])
  const [tempValue2, setTempValue2] = useState<number | undefined>(value?.[1])

  // options1 处理，如果tempValue2 已选择，则隐藏tempValue1 之后的所有选项 的选项
  const [options1, setOptions1] = useState<SelectOption<number>[]>(options)
  useEffect(() => {
    if(tempValue2){
      const index = findIndex(options, (item) => item.value === tempValue2)
      setOptions1(options.slice(0, index + 1))
    }else{
      setOptions1(options) // 如果被清空则变回展示所有
    }
  }, [tempValue2])

   // options2 处理，如果tempValue1 已选择，则隐藏tempValue1 之后的所有选项 的选项
   const [options2, setOptions2] = useState<SelectOption<number>[]>(options)
   useEffect(() => {
    if(tempValue1){
      const index = findIndex(options, (item) => item.value === tempValue1)
      setOptions2(options.slice(index))
    }else{
      setOptions2(options) // 如果被清空则变回展示所有
    }
   }, [tempValue1])
  

  // 判断是不是有效值
  const isValueValid = (value: (number | undefined)[]) => {
    // value只要有一个非undefined就返回true
    return value?.some((item) => item !== undefined)
  }

  // 外部点击清除所有
  const handleClearAll = () => {
    onChange?.([undefined, undefined])
    setTempValue1(undefined)
    setTempValue2(undefined)

    setOpen(false)
  }

  // trigger ---------------------------------------------------
  const defaultTrigger = (
    <div onClick={()=>{setOpen(true)}} className={classNames('ranger-layout group', {
        'ranger-layout--placeholder': !isValueValid(value || []),
        'ranger-layout--focus': open,
        'ranger-layout--disabled': disabled
      }, className)}>
      {/* 前缀 */}
      {prefix}
      {/* 文本 */}
      <div className={classNames('ranger-text')}>
        {isValueValid(value || []) ? (options.find((item) => item.value === value?.[0])?.label || 'Any') + ' - ' +  (options.find((item) => item.value === value?.[1])?.label || 'Any') : placeholder}
      </div>
      {/* 指示器 */}
      <div className='ranger-indicator'>
        <div className='ranger-indicator-container'>
          <ChevronDown className={classNames('ranger-indicator-arrow', {
            'rotate-180': open,
          })} />
        </div>
        <div className='ranger-indicator-container'>
          <X className={classNames('ranger-indicator-close opacity-0 group-hover:opacity-100 transition-all duration-100', {
            'hidden': !isValueValid(value || [])
          })}
            onClick={(e) => {
              e?.stopPropagation();
              handleClearAll();
            }}
          />
        </div>
      </div>
      {/* 后缀 */}
      {suffix}
    </div>
  )

  // content ---------------------------------------------------
  const content = (
    <div>
      <div className='flex gap-2 items-center justify-between mb-1'>
        <span className='flex-1 min-w-0 gap-2 shrink-0 font-semibold'>Min {name}</span>
        <span className='opacity-0'>-</span>
        <span className='flex-1 min-w-0 gap-2 shrink-0 font-semibold'>Max {name}</span>
      </div>
      <div className='flex gap-2 items-center'>
        <MySelect<number, false> name={'Start ' + name} prefix={<span className='opacity-50'>From</span>} className='flex-1' value={tempValue1} onChange={(value) => {
          setTempValue1(value)
        }} options={options1} />
        <span>-</span>
        <MySelect<number, false> name={'End ' + name} prefix={<span className='opacity-50'>To</span>} className='flex-1' value={tempValue2} onChange={(value) => {
          setTempValue2(value)
        }} options={options2} />
      </div>
      {/* <div className='flex gap-2 items-center'>
        <MyInput />
        <span>-</span>
        <MyInput />
      </div> */}
    </div>
  )

  return (
    <div>
      <FormModal open={open} onOpenChange={setOpen} 
        trigger={defaultTrigger}
        header={name}
        content={<div>
          {content}
        </div>}
        footer={<div className='flex gap-2'>
          <button className='flex-1 border border-black rounded-sm px-2 py-1 bg-transparent text-black' onClick={()=>{
            setTempValue1(undefined)
            setTempValue2(undefined)
          }}>Clear All</button>
          <button className='flex-1 border border-black rounded-sm px-2 py-1 bg-black text-white' onClick={()=>{
            onChange?.([tempValue1, tempValue2])
            setOpen(false)
          }}>
            Confirm
          </button>
        </div>}
      />
    </div>
  )
}

export default MyRanger